//
//  AWThemeManager.m
//  changeShin
//
//  Created by Alan Wang on 2019/3/25.
//  Copyright © 2019 Alan Wang. All rights reserved.
//

#import "AWThemeManager.h"
#import "AWTheme.h"

#import "UIImage+AWBuddle.h"

#define AW_JF_Default_Skin @"AW_JF_Default_Skin___"

static AWThemeManager* _instance = nil;

@interface AWThemeManager(){
    NSString * _skinName;
}
@property(nonatomic,strong) NSMutableDictionary * configDict;
@property(nonatomic,strong) NSMutableDictionary * themeDict;
@end


@implementation AWThemeManager
+(instancetype) shareInstance
{
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init] ;
    }) ;
    return _instance ;
    
}
-(instancetype)init{
    self = [super init];
    if (self) {
        _configDict = [[NSMutableDictionary alloc] init];
        _themeDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

//添加某个配置路径的皮肤
-(void)addConfigFilePath:(NSString*)path themeType:(AWThemeType)type{
    if(path){
        NSDictionary *configsFile = [NSDictionary dictionaryWithContentsOfFile:path];
        NSData *data = [NSData dataWithContentsOfFile:path];
        if (data){
            configsFile = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            if(configsFile){
                @synchronized(self) {
                    _configDict[path] = @(type);
                    _themeDict[path] = configsFile;
                }

            }
        }
    }
}
//移除某个路径的皮肤
-(void)removeConfigFilePath:(NSString*)path{
    @synchronized(self) {
        [self.configDict removeObjectForKey:path];
        [self.themeDict removeObjectForKey:path];
    }

}
//删除以前的所有添加的配置文件 新增Path下的文件
-(void)resetConfigWithFilePath:(NSString*)path themeType:(AWThemeType)type{
    [self removeAll];
    [self addConfigFilePath:path themeType:type];
}
//移除全部的皮肤文件
-(void)removeAll{
    @synchronized(self) {
        [self.configDict removeAllObjects];
        [self.themeDict removeAllObjects];
    }
}
//读取数据
-(UIImage*)imageForKey:(NSString*)key{
    UIImage * image = nil;
    if(key){
        for (NSString * themekey in self.themeDict.allKeys) {
            NSDictionary * dict  = self.themeDict[themekey];
            NSString *imageName = [dict valueForKeyPath:key];
            if(imageName){//只要找到key就会退出
                NSInteger flag = [[self.configDict valueForKey:themekey] integerValue];
                if (flag == AWThemeTypeSandbox) {
                    NSString * path = [themekey stringByDeletingLastPathComponent];
                    return [self imageFormPath:path name:imageName themeType:flag];
                }else{
                    return [self imageFormPath:imageName name:imageName themeType:flag];
                }
                
                break;
            }
        }
    }
    return image;
}
-(UIImage * )imageFormPath:(NSString*)path name:(NSString*)name themeType:(AWThemeType)type{
    if (type == AWThemeTypeSandbox) {
        UIImage * image = [self imageNameFromBuddle:name type:@"png" path:path];
        if(!image){
            image = [self imageNameFromBuddle:name type:@"jpg" path:path];
        }
        return image;
    }else{
        UIImage * image = [UIImage imageNamed:path];
        return image;
    }
}

-(UIColor*)colorForKey:(NSString*)key{
    UIColor * color = nil;
    for (NSString * themekey in self.themeDict.allKeys) {
        NSDictionary * dict  = self.themeDict[themekey];
        NSString *colorHexStr = [dict valueForKeyPath:key];
        if (colorHexStr) {//只要找到key就会退出
            color = [self colorWithHexString:colorHexStr];
            break;
        }
    }
    return color;
}
-(CGFloat)floatForKey:(NSString*)key{
    CGFloat vaule = 0;
    for (NSString * themekey in self.themeDict.allKeys) {
        NSDictionary * dict  = self.themeDict[themekey];
        NSString *vauleStr = [dict valueForKeyPath:key];
        if (vauleStr) {//只要找到key就会退出
            vaule = [vauleStr floatValue];
            break;
        }
    }
    return vaule;
}
-(BOOL)boolForKey:(NSString*)key{
    CGFloat flag = false;
    for (NSString * themekey in self.themeDict.allKeys) {
        NSDictionary * dict  = self.themeDict[themekey];
        NSString *vauleStr = [dict valueForKeyPath:key];
        if (vauleStr) {//只要找到key就会退出
            flag = [vauleStr boolValue];
            break;
        }
    }
    return flag;
}
-(NSString*)stringForKey:(NSString*)key{
    NSString *str = @"";
    for (NSString * themekey in self.themeDict.allKeys) {
        NSDictionary * dict  = self.themeDict[themekey];
        NSString *vauleStr = [dict valueForKeyPath:key];
        if (vauleStr) {//只要找到key就会退出
            str = vauleStr;
            break;
        }
    }
    return str;
}
-(NSUInteger)uIntegerForKey:(NSString*)key{
    NSUInteger tempInt = 0;
    for (NSString * themekey in self.themeDict.allKeys) {
        NSDictionary * dict  = self.themeDict[themekey];
        NSString *vauleStr = [dict valueForKeyPath:key];
        if (vauleStr) {//只要找到key就会退出
            tempInt = [vauleStr integerValue];
            break;
        }
    }
    return tempInt;
}
-(UIFont*)fontForKey:(NSString*)key{
    UIFont * font = nil;
    CGFloat size = [self floatForKey:key];
    font = [UIFont systemFontOfSize:size];
    return font;
}
-(UIFont*)boldfontForKey:(NSString*)key{
    UIFont * font = nil;
    CGFloat size = [self floatForKey:key];
    font = [UIFont boldSystemFontOfSize:size];
    return font;
}

#pragma mark--居于buddle图片的API
-(UIImage*)imageForName:(NSString*)key fromBudddle:(NSString*)buddleName{
    NSString * buddle = buddleName;
    if (self.skinName) {
        buddle = [NSString stringWithFormat:@"%@_%@",buddleName,self.skinName];
    }
   return [UIImage imageNameFromBuddle:key buddleName:buddle];
}


-(void)changeTheme{
      [[NSNotificationCenter defaultCenter] postNotificationName:AWThemeSkinChangeNotification object:nil];
}
#pragma mark--辅助方法
- (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

-(UIImage*)imageNameFromBuddle:(NSString*)name type:(NSString*)type path:(NSString*)path{
    
    UIImage * image = nil;
    NSString *imagePath = [NSString stringWithFormat:@"%@//%@.%@",path,name,type];
    NSString *imagePath2x = [NSString stringWithFormat:@"%@//%@@2x.%@",path,name,type];
    NSString *imagePath3x = [NSString stringWithFormat:@"%@//%@@3x.%@",path,name,type];
    
    if(3 == [UIScreen mainScreen].scale) //3x下优先获取高清图片
    {
        image = [UIImage imageWithContentsOfFile:imagePath3x];
        if(nil == image)
        {
            image = [UIImage imageWithContentsOfFile:imagePath2x];
        }
    }
    else if(2 == [UIScreen mainScreen].scale)
    {
        image = [UIImage imageWithContentsOfFile:imagePath2x];
        if(nil == image)
        {
            image = [UIImage imageWithContentsOfFile:imagePath];
        }
    }
    if(nil == image)
    {
        image = [UIImage imageWithContentsOfFile:imagePath];
    }
    return image;
}

#pragma mark--懒加载
-(void)setSkinName:(NSString *)skinName{
    if (skinName && skinName.length) {
        _skinName = skinName;
         [[NSUserDefaults standardUserDefaults] setObject:skinName forKey:AW_JF_Default_Skin];
    }
}
-(NSString*)skinName{
    id vaule =  [[NSUserDefaults standardUserDefaults] objectForKey:AW_JF_Default_Skin];
    if (!vaule) {
        return @"";
    }else{
        return vaule;
    }
}
@end
